<?php
/**
 * Created by PhpStorm.
 * User: hoter.zhang
 * Date: 2016/5/11
 * Time: 16:57
 */

namespace app\core\components;


class RSA
{
    /**
     * public_key.pem 加密
     * @param $data
     * @param $public_key_path
     * @return mixed
     */
    public static function publicKey_encode($data, $public_key_path){
        $pubKey = file_get_contents($public_key_path);
        $res = openssl_get_publickey($pubKey);
        if (openssl_public_encrypt($data,$encrypt,$res)){
            return base64_encode("".$encrypt);
        }
    }

    /**
     * private_key.pem 解密
     * @param $content
     * @param $private_key_path
     * @return string
     */
    public static function privateKey_decode($content, $private_key_path){
        $priKey = file_get_contents($private_key_path);
        $res = openssl_get_privatekey($priKey);
        $content = base64_decode($content);//還原成二進制
        $result = '';
        for ($i=0; $i < strlen($content)/128; $i++) {
            $data = substr($content, $i*128, 128);
            openssl_private_decrypt($data,$decrypt,$res);
            $result .= $decrypt;
        }
        openssl_free_key($res);
        return $result;
    }
    
}